package com.mxnet.chongjin.supoman.activity;

import android.app.Instrumentation;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.bean.AppointBean;
import com.mxnet.chongjin.supoman.bean.Appointment;
import com.mxnet.chongjin.supoman.config.Api;
import com.mxnet.chongjin.supoman.utils.LoggerUtils;
import com.mxnet.chongjin.supoman.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

public class SetAppointmentActivity extends AppCompatActivity implements View.OnClickListener {
    private Context mContext;
    private LinearLayout mLinearLayout;
    private TextView mChronometer;
    private TextView mTvLeft, mTvRight;
    private SwipeMenuLayout mTv1, mTv2, mTv3;
    private ImageView mIvLeft, mIvRight;
    private int mTvLeftState, mTvRightState;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private Button mBtn1, mBtn2, mBtn3, mButton;
    private int pointCount;
    private SharedPreferences mPreferences;
    private SharedPreferences.Editor mEditor;
    private List<Appointment> mList, list;
    private List<String> delList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_appointment);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);

        mContext = SetAppointmentActivity.this;
        mPreferences = getSharedPreferences("supoman", MODE_PRIVATE);
        mEditor = mPreferences.edit();

        initView();
        initData();
    }

    public void initView() {
        mLinearLayout = findViewById(R.id.ll_set_appointment);
        mLinearLayout.setOnClickListener(this);

        mChronometer = findViewById(R.id.chronometer_set_appointment);

        mButton = findViewById(R.id.btn_set_appointment);
        mButton.setOnClickListener(this);

        mTvLeft = findViewById(R.id.tv_set_appointment_left);
        mTvLeft.setOnClickListener(this);
        mTvLeft.setClickable(false);

        mIvLeft = findViewById(R.id.iv_set_appointment_left);

        mTvRight = findViewById(R.id.tv_set_appointment_right);
        mTvRight.setOnClickListener(this);

        mIvRight = findViewById(R.id.iv_set_appointment_right);

        mTv1 = findViewById(R.id.tv_set_appointment_1);

        mTv2 = findViewById(R.id.tv_set_appointment_2);

        mTv3 = findViewById(R.id.tv_set_appointment_3);

        mBtn1 = findViewById(R.id.btn_set_appointment_1);
        mBtn1.setOnClickListener(this);

        mBtn2 = findViewById(R.id.btn_set_appointment_2);
        mBtn2.setOnClickListener(this);

        mBtn3 = findViewById(R.id.btn_set_appointment_3);
        mBtn3.setOnClickListener(this);
    }

    public void initData() {
        mTvLeftState = 0;
        mTvRightState = 0;
        pointCount = 0;
        mList = new ArrayList<Appointment>();
        list = new ArrayList<Appointment>();
        delList = new ArrayList<String>();

        mTimer = new Timer();

        OkHttpUtils.get()
                .url(Api.URL_HEADER + Api.GET_APPOINTMENT)
                .addParams("mac", mPreferences.getString("MAC", "000.000.000.000"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                boolean isSuccess = jsonObject.optBoolean("success");
                                if (isSuccess) {
                                    JSONObject data = jsonObject.optJSONObject("data");
                                    JSONArray memoryPoints = data.optJSONArray("memoryPoints");
                                    for (int i = 0; i < memoryPoints.length(); i++) {
                                        Appointment appointment = new Appointment();
                                        JSONObject object = memoryPoints.optJSONObject(i);
                                        appointment.setCreateTime(object.optLong("createTime"));
                                        appointment.setDelFlag(object.optBoolean("delFlag"));
                                        appointment.setId(object.getString("id"));
                                        appointment.setMac(object.optString("mac"));
                                        appointment.setName(object.optString("name"));
                                        appointment.setNeedSeconds(object.optString("needSeconds"));
                                        mList.add(appointment);
                                    }

                                    if (mList.size() == 0) {
                                        mTv1.setVisibility(View.INVISIBLE);
                                        mTv2.setVisibility(View.INVISIBLE);
                                        mTv3.setVisibility(View.INVISIBLE);
                                        mEditor.putInt("point1", 0);
                                        mEditor.putInt("point2", 0);
                                        mEditor.putInt("point3", 0);
                                        mEditor.commit();
                                    } else if (mList.size() == 1) {
                                        if (!mList.get(0).getNeedSeconds().equals("0")) {
                                            mTv1.setVisibility(View.VISIBLE);
                                        }
                                        mTv2.setVisibility(View.INVISIBLE);
                                        mTv3.setVisibility(View.INVISIBLE);
                                        mEditor.putInt("point1", Integer.parseInt(mList.get(0).getNeedSeconds()));
                                        mEditor.putInt("point2", 0);
                                        mEditor.putInt("point3", 0);
                                        mEditor.commit();
                                    } else if (mList.size() == 2) {
                                        if (!mList.get(0).getNeedSeconds().equals("0")) {
                                            mTv1.setVisibility(View.VISIBLE);
                                        }
                                        if (!mList.get(1).getNeedSeconds().equals("0")) {
                                            mTv2.setVisibility(View.VISIBLE);
                                        }
                                        mTv3.setVisibility(View.INVISIBLE);
                                        mEditor.putInt("point1", Integer.parseInt(mList.get(0).getNeedSeconds()));
                                        mEditor.putInt("point2", Integer.parseInt(mList.get(1).getNeedSeconds()));
                                        mEditor.putInt("point3", 0);
                                        mEditor.commit();
                                    } else if (mList.size() == 3) {
                                        if (!mList.get(0).getNeedSeconds().equals("0")) {
                                            mTv1.setVisibility(View.VISIBLE);
                                        }
                                        if (!mList.get(1).getNeedSeconds().equals("0")) {
                                            mTv2.setVisibility(View.VISIBLE);
                                        }
                                        if (!mList.get(2).getNeedSeconds().equals("0")) {
                                            mTv3.setVisibility(View.VISIBLE);
                                        }
                                        mEditor.putInt("point1", Integer.parseInt(mList.get(0).getNeedSeconds()));
                                        mEditor.putInt("point2", Integer.parseInt(mList.get(1).getNeedSeconds()));
                                        mEditor.putInt("point3", Integer.parseInt(mList.get(2).getNeedSeconds()));
                                        mEditor.commit();
                                    } else {
                                        if (!mList.get(0).getNeedSeconds().equals("0")) {
                                            mTv1.setVisibility(View.VISIBLE);
                                        }
                                        if (!mList.get(1).getNeedSeconds().equals("0")) {
                                            mTv2.setVisibility(View.VISIBLE);
                                        }
                                        if (!mList.get(2).getNeedSeconds().equals("0")) {
                                            mTv3.setVisibility(View.VISIBLE);
                                        }
                                        mEditor.putInt("point1", Integer.parseInt(mList.get(0).getNeedSeconds()));
                                        mEditor.putInt("point2", Integer.parseInt(mList.get(1).getNeedSeconds()));
                                        mEditor.putInt("point3", Integer.parseInt(mList.get(2).getNeedSeconds()));
                                        mEditor.commit();
                                    }
                                    LoggerUtils.i("*******", mList.size() + "");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    int cnt = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_set_appointment:
                back();
                break;
            case R.id.tv_set_appointment_left:
                switch (mTvLeftState) {
                    case 0:
                        if (mTv1.getVisibility() == View.INVISIBLE) {
                            mTv1.setVisibility(View.VISIBLE);
                            mEditor.putInt("point1", cnt / 100);
                            mEditor.commit();
                        } else if (mTv1.getVisibility() == View.VISIBLE && mTv2.getVisibility() == View.INVISIBLE) {
                            if ((cnt / 100) <= mPreferences.getInt("point1", 0)) {
                                ToastUtils.showToast(mContext, getResources().getString(R.string.time_short));
                            } else {
                                mTv2.setVisibility(View.VISIBLE);
                                mEditor.putInt("point2", cnt / 100);
                                mEditor.commit();
                            }
                        } else if (mTv1.getVisibility() == View.VISIBLE && mTv2.getVisibility() == View.VISIBLE && mTv3.getVisibility() == View.INVISIBLE) {
                            if ((cnt / 100) <= mPreferences.getInt("point2", 0)) {
                                ToastUtils.showToast(mContext, getResources().getString(R.string.time_short));
                            } else {
                                mTv3.setVisibility(View.VISIBLE);
                                mEditor.putInt("point3", cnt / 100);
                                mEditor.commit();
                            }
                        } else {
                            Toast.makeText(mContext, getResources().getString(R.string.three_most), Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 1:
                        mTv1.setVisibility(View.INVISIBLE);
                        mTv2.setVisibility(View.INVISIBLE);
                        mTv3.setVisibility(View.INVISIBLE);
                        mTv1.quickClose();
                        mTv2.quickClose();
                        mTv3.quickClose();
                        cnt = 0;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mChronometer.setText("00:00.00");
                            }
                        });
                        mEditor.putInt("point1", 0);
                        mEditor.putInt("point2", 0);
                        mEditor.putInt("point3", 0);
                        mEditor.commit();
                        break;
                }
                break;
            case R.id.tv_set_appointment_right:
                switch (mTvRightState) {
                    case 0:
                        mTvRightState = 1;
                        mTvLeftState = 0;

                        mIvLeft.setImageResource(R.mipmap.set_appointment_gray);
                        mTvLeft.setText(getResources().getString(R.string.set_appointment));
                        mTvLeft.setTextColor(getResources().getColor(R.color.colorWhite));
                        mTvLeft.setClickable(true);

                        mIvRight.setImageResource(R.mipmap.set_appointment_pink);
                        mTvRight.setText(getResources().getString(R.string.stop));
                        mTvRight.setTextColor(getResources().getColor(R.color.net_next));

                        mTimerTask = new TimerTask() {
                            @Override
                            public void run() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mChronometer.setText(getStringTime(cnt++));
                                    }
                                });
                            }
                        };
                        mTimer.schedule(mTimerTask, 0, 10);
                        break;
                    case 1:
                        mTvRightState = 0;
                        mTvLeftState = 1;

                        mIvLeft.setImageResource(R.mipmap.set_appointment_gray);
                        mTvLeft.setText(getResources().getString(R.string.clear));
                        mTvLeft.setTextColor(getResources().getColor(R.color.colorWhite));
                        mTvLeft.setClickable(true);

                        mIvRight.setImageResource(R.mipmap.set_appointment_blue);
                        mTvRight.setText(getResources().getString(R.string.start));
                        mTvRight.setTextColor(getResources().getColor(R.color.set_appointment_blue));

                        if (!mTimerTask.cancel()) {
                            mTimerTask.cancel();
                            mTimer.cancel();
                        }
                        break;
                }
                break;
            case R.id.btn_set_appointment_1:
                deleteAppointment();
                break;
            case R.id.btn_set_appointment_2:
                deleteAppointment();
                break;
            case R.id.btn_set_appointment_3:
                deleteAppointment();
                break;
            case R.id.btn_set_appointment:
                final int point1 = mPreferences.getInt("point1", 0);
                int point2 = mPreferences.getInt("point2", 0);
                int point3 = mPreferences.getInt("point3", 0);
                LoggerUtils.i("*******##", mList.size() + "" + "\t" + point1 + "\t" + point2 + "\t" + point3);
                switch (mList.size()) {
                    case 0:
                        if (point1 == 0) {

                        } else if (point2 == 0) {
                            Appointment a = new Appointment();
                            a.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            a.setName("point1");
                            a.setNeedSeconds(point1 + "");
                            list.add(a);
                        } else if (point3 == 0) {
                            Appointment a = new Appointment();
                            a.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            a.setName("point1");
                            a.setNeedSeconds(point1 + "");
                            list.add(a);
                            Appointment b = new Appointment();
                            b.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            b.setName("point2");
                            b.setNeedSeconds(point2 + "");
                            list.add(b);
                        } else {
                            Appointment a = new Appointment();
                            a.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            a.setName("point1");
                            a.setNeedSeconds(point1 + "");
                            list.add(a);
                            Appointment b = new Appointment();
                            b.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            b.setName("point2");
                            b.setNeedSeconds(point2 + "");
                            list.add(b);
                            Appointment c = new Appointment();
                            c.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            c.setName("point3");
                            c.setNeedSeconds(point3 + "");
                            list.add(c);
                        }
                        break;
                    case 1:
                        if (point1 == 0) {
                            delList.add(mList.get(0).getId());
                        } else if (point2 == 0) {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                }
                            }
                        } else if (point3 == 0) {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                }
                            }
                            Appointment b = new Appointment();
                            b.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            b.setName("point2");
                            b.setNeedSeconds(point2 + "");
                            list.add(b);
                        } else {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                }
                            }
                            Appointment b = new Appointment();
                            b.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            b.setName("point2");
                            b.setNeedSeconds(point2 + "");
                            list.add(b);
                            Appointment c = new Appointment();
                            c.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            c.setName("point3");
                            c.setNeedSeconds(point3 + "");
                            list.add(c);
                        }
                        break;
                    case 2:
                        if (point1 == 0) {
                            for (Appointment a : mList) {
                                delList.add(a.getId());
                            }
                        } else if (point2 == 0) {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                } else {
                                    delList.add(a.getId());
                                }
                            }
                        } else if (point3 == 0) {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                } else if (a.getName().equals("point2")) {
                                    a.setNeedSeconds(point2 + "");
                                    list.add(a);
                                }
                            }
                        } else {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                } else if (a.getName().equals("point2")) {
                                    a.setNeedSeconds(point2 + "");
                                    list.add(a);
                                }
                            }
                            Appointment c = new Appointment();
                            c.setMac(mPreferences.getString("MAC", "000.000.000.000"));
                            c.setName("point3");
                            c.setNeedSeconds(point3 + "");
                            list.add(c);
                        }
                        break;
                    case 3:
                        if (point1 == 0) {
                            for (Appointment a : mList) {
                                delList.add(a.getId());
                            }
                        } else if (point2 == 0) {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                } else {
                                    delList.add(a.getId());
                                }
                            }
                        } else if (point3 == 0) {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                } else if (a.getName().equals("point2")) {
                                    a.setNeedSeconds(point2 + "");
                                    list.add(a);
                                } else {
                                    delList.add(a.getId());
                                }
                            }
                        } else {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                } else if (a.getName().equals("point2")) {
                                    a.setNeedSeconds(point2 + "");
                                    list.add(a);
                                } else if (a.getName().equals("point3")) {
                                    a.setNeedSeconds(point3 + "");
                                    list.add(a);
                                } else {
                                    delList.add(a.getId());
                                }
                            }
                        }
                        break;
                    default:
                        if (point1 == 0) {
                            for (Appointment a : mList) {
                                delList.add(a.getId());
                            }
                        } else if (point2 == 0) {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                } else {
                                    delList.add(a.getId());
                                }
                            }
                        } else if (point3 == 0) {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                } else if (a.getName().equals("point2")) {
                                    a.setNeedSeconds(point2 + "");
                                    list.add(a);
                                } else {
                                    delList.add(a.getId());
                                }
                            }
                        } else {
                            for (Appointment a : mList) {
                                if (a.getName().equals("point1")) {
                                    a.setNeedSeconds(point1 + "");
                                    list.add(a);
                                } else if (a.getName().equals("point2")) {
                                    a.setNeedSeconds(point2 + "");
                                    list.add(a);
                                } else if (a.getName().equals("point3")) {
                                    a.setNeedSeconds(point3 + "");
                                    list.add(a);
                                } else {
                                    delList.add(a.getId());
                                }
                            }
                        }
                        break;
                }
                final AppointBean a = new AppointBean();
                a.setList(list);
                if (list.size() == 0) {

                } else {
                    OkHttpUtils.get()
                            .url(Api.URL_HEADER + Api.SET_APPOINTMENT)
                            .addParams("data", new Gson().toJson(a))
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {

                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    LoggerUtils.i("******&&&&&&&&", Api.URL_HEADER + Api.SET_APPOINTMENT + "\t" + new Gson().toJson(a));
                                    if (!TextUtils.isEmpty(response)) {
                                        LoggerUtils.i("******", response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            boolean isSuccess = jsonObject.optBoolean("success");
                                            if (isSuccess) {
                                                ToastUtils.showToast(mContext, getResources().getString(R.string.set_success));
                                                JSONArray data = jsonObject.optJSONArray("data");
                                                for (int i = 0; i < data.length(); i ++) {
                                                    JSONObject object = data.optJSONObject(i);
                                                    String name = object.optString("name");
                                                    if (name.equals("point1")) {
                                                        mEditor.putString("point1Id", object.optString("id"));
                                                        mEditor.commit();
                                                    }
                                                    if (name.equals("point2")) {
                                                        mEditor.putString("point2Id", object.optString("id"));
                                                        mEditor.commit();
                                                    }
                                                    if (name.equals("point3")) {
                                                        mEditor.putString("point3Id", object.optString("id"));
                                                        mEditor.commit();
                                                    }
                                                }
                                            } else {
                                                ToastUtils.showToast(mContext, getResources().getString(R.string.set_failed));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            });
                }
                if (delList.size() == 0) {

                } else {
                    for (String str : delList) {
                        OkHttpUtils.get()
                                .url(Api.URL_HEADER + Api.DEL_APPOINTMENT)
                                .addParams("id", str)
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {

                                    }

                                    @Override
                                    public void onResponse(String response, int id) {

                                    }
                                });
                    }
                }

                back();
                break;
        }
    }

    private void deleteAppointment() {
        if (mTv3.getVisibility() == View.VISIBLE) {
            mTv3.setVisibility(View.INVISIBLE);
            mEditor.putInt("point3", 0);
        } else if (mTv2.getVisibility() == View.VISIBLE) {
            mTv2.setVisibility(View.INVISIBLE);
            mEditor.putInt("point2", 0);
        } else if (mTv1.getVisibility() == View.VISIBLE) {
            mTv1.setVisibility(View.INVISIBLE);
            mEditor.putInt("point1", 0);
        }
        mTv1.quickClose();
        mTv2.quickClose();
        mTv3.quickClose();
        mEditor.commit();
    }

    private String getStringTime(int cnt) {
        int min = cnt / 6000 % 60;
        int sec = cnt / 100 % 60;
        int msec = cnt % 100;
        return String.format(Locale.CHINA, "%02d:%02d.%02d", min, sec, msec);
    }

    private void back() {
        new Thread() {
            public void run() {
                try {
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private int getPointCount() {
        int point1 = mPreferences.getInt("point1", 0);
        int point2 = mPreferences.getInt("point2", 0);
        int point3 = mPreferences.getInt("point3", 0);
        if (point1 == 0) {
            return 0;
        } else if (point2 == 0) {
            return 1;
        } else if (point3 == 0) {
            return 2;
        } else {
            return 3;
        }
    }
}
